<!DOCTYPE html>
<html lang=zh-CN>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta property="og:description" content="samuel-24276的博客">
    <meta property="og:type" content="website">
    <meta name="description" content="samuel-24276的博客">
    <meta name="keyword"  content="aircloud">
    <link rel="shortcut icon" href="/myblog/img/favicon.ico">

    <title>
        
        QT学习日记（5）——QFile文件操作 - samuel-24276的博客 | samuel-24276&#39;s Blog
        
    </title>

    <!-- Custom CSS -->
    
<link rel="stylesheet" href="/myblog/css/aircloud.css">

    
<link rel="stylesheet" href="/myblog/css/gitment.css">

    <!--<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">-->
    <link href="//at.alicdn.com/t/font_620856_28hi1hpxx24.css" rel="stylesheet" type="text/css">
    <!-- ga & ba script hoook -->
    <script></script>
<meta name="generator" content="Hexo 7.1.1"></head>

<body>

<div class="site-nav-toggle" id="site-nav-toggle">
    <button>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
        <span class="btn-bar"></span>
    </button>
</div>

<div class="index-about">
    <i> Like what you do, do what you like </i>
</div>

<div class="index-container">
    
    <div class="index-left">
        
<div class="nav" id="nav">
    <div class="avatar-name">
        <div class="avatar ">
            <img src="/myblog/img/avatar.jpg" />
        </div>
        <div class="name">
            <i>samuel-24276</i>
        </div>
    </div>
    <div class="contents" id="nav-content">
        <ul>
            <li >
                <a href="/myblog/">
                    <i class="iconfont icon-shouye1"></i>
                    <span>主页</span>
                </a>
            </li>
            <li >
                <a href="/myblog/tags">
                    <i class="iconfont icon-biaoqian1"></i>
                    <span>标签</span>
                </a>
            </li>
            <li >
                <a href="/myblog/archives">
                    <i class="iconfont icon-guidang2"></i>
                    <span>存档</span>
                </a>
            </li>
            <li >
                <a href="/myblog/collect/">
                    <i class="iconfont icon-shoucang1"></i>
                    <span>收藏</span>
                </a>
            </li>
            <li >
                <a href="/myblog/about/">
                    <i class="iconfont icon-guanyu2"></i>
                    <span>关于</span>
                </a>
            </li>
            
            <li>
                <a id="search">
                    <i class="iconfont icon-sousuo1"></i>
                    <span>搜索</span>
                </a>
            </li>
            
        </ul>
    </div>
    
        <div id="toc" class="toc-article">
    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#15-QFile%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C"><span class="toc-text">15.QFile文件操作</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#15-1-%E8%AF%BB%E6%96%87%E4%BB%B6"><span class="toc-text">15.1.读文件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#15-2-%E5%86%99%E6%96%87%E4%BB%B6"><span class="toc-text">15.2.写文件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#15-3-QFileInfo%E6%96%87%E4%BB%B6%E4%BF%A1%E6%81%AF%E7%B1%BB"><span class="toc-text">15.3.QFileInfo文件信息类</span></a></li></ol></li></ol>
</div>
    
</div>


<div class="search-field" id="search-field">
    <div class="search-bg" id="search-bg"></div>
    <div class="search-container">
        <div class="search-input">
            <span id="esc-search"> <i class="icon-fanhui iconfont"></i></span>
            <input id="search-input"/>
            <span id="begin-search">搜索</span>
        </div>
        <div class="search-result-container" id="search-result-container">

        </div>
    </div>
</div>

        <div class="index-about-mobile">
            <i> Like what you do, do what you like </i>
        </div>
    </div>
    
    <div class="index-middle">
        <!-- Main Content -->
        


<div class="post-container">
    <div class="post-title">
        QT学习日记（5）——QFile文件操作
    </div>

    <div class="post-meta">
        <span class="attr">发布于：<span>2019-10-19 10:15:38</span></span>
        
        <span class="attr">标签：/
        
        <a class="tag" href="/myblog/tags/#Qt" title="Qt">Qt</a>
        <span>/</span>
        
        
        </span>
        <span class="attr">访问：<span id="busuanzi_value_page_pv"></span>
</span>
</span>
    </div>
    <div class="post-content no-indent">
        <h1 id="15-QFile文件操作"><a href="#15-QFile文件操作" class="headerlink" title="15.QFile文件操作"></a>15.QFile文件操作</h1><p>新建项目QFile，向widget.ui拖入单行文本框和一个按钮，并将它们放在一个widget中，水平布局，再向widget拖入一个Text Edit文本框，垂直布局。将按钮命名为选取按钮，更改类名为btn，向widget.cpp增添头文件</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;QFileDialog&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;QDebug&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;QFile&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;QMessageBox&gt;</span><span class="comment">//提示信息 </span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;QTextCodec&gt;</span></span></span><br></pre></td></tr></table></figure>
<p>在构造函数里添加代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//点击按钮，选择文件</span></span><br><span class="line"><span class="built_in">connect</span>(ui-&gt;btn, &amp;QPushButton::clicked, [=]()&#123;</span><br><span class="line">	<span class="comment">//第一参数是打开的窗口，第二参数是窗口名字，第三参数是默认的打开路径,第四参数是选取得文件类型</span></span><br><span class="line">	QString filePath = QFileDialog::<span class="built_in">getOpenFileName</span>(<span class="keyword">this</span>, <span class="string">&quot;选择文件&quot;</span>, <span class="string">&quot;D:\\CODE\\QT\\06-02\\QFile&quot;</span>, <span class="string">&quot;(*.txt)&quot;</span>);</span><br><span class="line">	<span class="comment">//qDebug()&lt;&lt;filePath;</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">//如果用户取消打开文件</span></span><br><span class="line">	<span class="keyword">if</span>(filePath.<span class="built_in">isEmpty</span>())</span><br><span class="line">	&#123;</span><br><span class="line">		QMessageBox::<span class="built_in">warning</span>(<span class="keyword">this</span>, <span class="string">&quot;打开失败&quot;</span>, <span class="string">&quot;文件路径为空&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">//将文件路径放入到LineEdit中</span></span><br><span class="line">	ui-&gt;lineEdit-&gt;<span class="built_in">setText</span>(filePath);</span><br><span class="line"></span><br><span class="line">	<span class="comment">//将文件中的内容放入TextEdit</span></span><br><span class="line">	QFile <span class="built_in">file</span>(filePath);<span class="comment">//默认支持格式是utf-8</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">//设置文本编码格式</span></span><br><span class="line">	<span class="comment">//QTextCodec * codec = QTextCodec::codecForName(&quot;gbk&quot;);</span></span><br><span class="line">	<span class="comment">//设置打开方式</span></span><br><span class="line">	file.<span class="built_in">open</span>(QIODevice::ReadOnly);</span><br><span class="line">	QByteArray arr;</span><br><span class="line">	<span class="comment">//arr = file.readAll();//一次性读取所有文件内容</span></span><br><span class="line"></span><br><span class="line">	<span class="keyword">while</span>(!file.<span class="built_in">atEnd</span>())</span><br><span class="line">	&#123;</span><br><span class="line">		arr += file.<span class="built_in">readLine</span>();<span class="comment">//按行读取数据</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	ui-&gt;textEdit-&gt;<span class="built_in">setText</span>(arr);</span><br><span class="line">	<span class="comment">//ui-&gt;textEdit-&gt;setText(codec-&gt;toUnicode(arr));</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">//关闭文件对象</span></span><br><span class="line">	file.<span class="built_in">close</span>();</span><br><span class="line"></span><br><span class="line">	<span class="comment">//写文件</span></span><br><span class="line">	file.<span class="built_in">open</span>(QIODevice::Append);<span class="comment">//利用追加的方式修改</span></span><br><span class="line">	file.<span class="built_in">write</span>(<span class="string">&quot;我是傻逼&quot;</span>);</span><br><span class="line"></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h2 id="15-1-读文件"><a href="#15-1-读文件" class="headerlink" title="15.1.读文件"></a>15.1.读文件</h2><ul>
<li>1.QFile file(文件路径)打开文件</li>
<li>2.file.open(QIODevice::ReadOnly);指定打开方式为只读</li>
<li>3.file.readAll()一次性读文件所有内容，file.readLine()一次读取文件得一行内容，file.atEnd()判断是否到达文件末尾</li>
<li>4.指定编码格式,默认是utf-8  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">QTextCodec * codec = QTextCodec::<span class="built_in">codecForName</span>(<span class="string">&quot;gbk&quot;</span>);</span><br><span class="line">ui-&gt;textEdit-&gt;<span class="built_in">setText</span>(codec-&gt;<span class="built_in">toUnicode</span>(arr));</span><br></pre></td></tr></table></figure></li>
<li>5.file.close()关闭文件对象</li>
</ul>
<h2 id="15-2-写文件"><a href="#15-2-写文件" class="headerlink" title="15.2.写文件"></a>15.2.写文件</h2><ul>
<li>1.file.open(QIODevice::Append);指定打开方式为追加，若是只读的话，则应用QIODevice::ReadOnly</li>
<li>2.file.write()往文件内写入内容</li>
<li>3.其他操作同读文件相同</li>
</ul>
<h2 id="15-3-QFileInfo文件信息类"><a href="#15-3-QFileInfo文件信息类" class="headerlink" title="15.3.QFileInfo文件信息类"></a>15.3.QFileInfo文件信息类</h2><p>先注释掉之前的写文件代码，添加头文件：<code>#include&lt;QFileInfo&gt;</code>,打开帮助文档搜索QFileInfo并找到其Public Functions,即可查看到文件的各种信息函数，比较实用的是<code>QString suffix() const</code>，它可以获取文件的后缀名。在Lambda表达式里添加代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">QFileInfo <span class="title">info</span><span class="params">(filePath)</span></span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">qDebug</span>()&lt;&lt;<span class="string">&quot;大小&quot;</span>&lt;&lt;info.<span class="built_in">size</span>()&lt;&lt;<span class="string">&quot;后缀名&quot;</span>&lt;&lt;info.<span class="built_in">suffix</span>()&lt;&lt;<span class="string">&quot;文件路径&quot;</span>&lt;&lt;info.<span class="built_in">filePath</span>();</span><br><span class="line"><span class="built_in">qDebug</span>()&lt;&lt;<span class="string">&quot;创建日期&quot;</span>&lt;&lt;info.<span class="built_in">created</span>().<span class="built_in">toString</span>(<span class="string">&quot;yyyy/MM/dd hh:mm:ss&quot;</span>);</span><br><span class="line"><span class="built_in">qDebug</span>()&lt;&lt;<span class="string">&quot;最后修改日期&quot;</span>&lt;&lt;info.<span class="built_in">lastModified</span>().<span class="built_in">toString</span>(<span class="string">&quot;yyyy/MM/dd hh:mm:ss&quot;</span>);</span><br></pre></td></tr></table></figure>
<ul>
<li>1.QFileInfo info(文件路径)</li>
<li>2.created()文件创建日期、lastModified()文件最后修改日期，它们有函数toString(“yyyy&#x2F;MM&#x2F;dd hh:mm:ss”)可以把日期格式化输出，注意引号里的内容不要写错，否则输出不对。</li>
<li>3其他文件信息，如文件名，后缀名等均可以在帮助文档里搜索QFileInfo并找到其Public Functions，里面可以看到各类文件信息。</li>
</ul>
<hr>

        
            <div class="donate-container">
    <div class="donate-button">
        <button id="donate-button">赞赏</button>
    </div>
    <div class="donate-img-container hide" id="donate-img-container">
        <img id="donate-img" src="" data-src="/myblog/img/donate.jpg">
        <p> 感谢鼓励 </p>
    </div>
</div>
        
        <br />
        <div id="comment-container">
        </div>
        <div id="disqus_thread"></div>
        <div id="lv-container"></div>
        <div class="giscus"></div>
    </div>
</div>

    </div>
</div>


<footer class="footer">
    <ul class="list-inline text-center">
        
        

        

        

        
        <li>
            <a target="_blank"  href="https://github.com/samuel-24276">
                            <span class="fa-stack fa-lg">
                                <i class="iconfont icon-github"></i>
                            </span>
            </a>
        </li>
        

        

    </ul>
    
    <p>
        <span>/</span>
        
        <span><a target="_blank" rel="noopener" href="https://github.com/samuel-24276">samuel-24276&#39;s Page</a></span>
        <span>/</span>
        
        <span><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/">北京-未备案</a></span>
        <span>/</span>
        
        <span><a href="#">返回顶部</a></span>
        <span>/</span>
        
    </p>
    
    <p>
        <span id="busuanzi_container_site_pv">
            <span id="busuanzi_value_site_pv"></span>PV
        </span>
        <span id="busuanzi_container_site_uv">
            <span id="busuanzi_value_site_uv"></span>UV
        </span>
        Created By <a target="_blank" rel="noopener" href="https://hexo.io/">Hexo</a>  Theme <a target="_blank" rel="noopener" href="https://github.com/aircloud/hexo-theme-aircloud">AirCloud</a></p>
</footer>




</body>

<script>
    // We expose some of the variables needed by the front end
    window.hexo_search_path = "search.json"
    window.hexo_root = "/myblog/"
    window.isPost = true
</script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>

<script src="/myblog/js/index.js"></script>

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>






    <script type="text/javascript">
       (function() {
           if (typeof LivereTower === 'function') { return; }

           var j, d = document.getElementById('lv-container');

           d.setAttribute('data-id','city');
           d.setAttribute('data-uid' , 'MTAyMC80OTA5OC8yNTU5Mw==');

           j = document.createElement('script');
           j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
           j.async = true;

           d.appendChild(j);
       })();
    </script>
    <noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
    </div>

</html>
